package com.ruoyi.uitity;
import com.rabbitmq.client.Channel;
import com.ruoyi.domain.Wxmessage;
import com.ruoyi.framework.config.RabbitConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class WxMessageConsumer {

    @Autowired
    private BaiduChatBot baiduChatBot;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitConfig.QUEUE_NAME)
    @SendTo()
    public String receiveMessage(String message, Channel channel, Message msg) throws IOException {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try {
            // 连接百度千帆接口
            baiduChatBot.createConversation();

            // 处理消息，例如调用百度千帆接口
            String result = baiduChatBot.query(message);
            log.info("Message processed: {}", result);

            // 手动确认消息
            channel.basicAck(deliveryTag, false);
            return result; // 返回处理结果
        } catch (Exception e) {
            // 异常处理：记录日志或采取其他补救措施
            log.error("处理消息时发生错误: {}", e.getMessage(), e);

            // 拒绝确认消息，并将其重新入队
            try {
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException ioException) {
                log.error("消息确认失败: {}", ioException.getMessage(), ioException);
            }
            return null; // 或者返回错误信息
        }
    }
}
